﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WoChu.RfClient.Entity;
using WoChu.RfClient.Common;
using WoChu.CF.BaseFrame.Util;

namespace WoChu.RfClient.Duty
{
    public partial class FrmOffShelvesOrderWC : Form
    {
        public FrmOffShelvesOrderWC()
        {
            InitializeComponent();
        } 
 
        private List<OffShelvesInfo> lstOffShelves = new List<OffShelvesInfo>();
        private string IsCellno = null;
        //private static string OffBatch = null;

        //状态加载事件
        private void FrmOffShelvesOrder_Load(object sender, EventArgs e)
        {
            FrmCellno frmCl = new FrmCellno();
            frmCl.ShowDialog();

            if (FrmCellno.IsOK)
            {
                IsCellno = FrmCellno.valCellno;
            }
            else
            {
                this.Close();
                return;
            }
            this.Text = string.Format("{0}--{1}", this.Text, IsCellno);

            this.dtDeliveryDate.Value = DateTime.Now;
            this.dtDeliveryDate.Focus();
        }
 
        //获取下架指令
        private void btnShelves_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime offDT = dtDeliveryDate.Value;
                if (string.IsNullOrEmpty(offDT.ToString()))
                {
                    MessageBox.Show("配送日期不能为空！");
                    dtDeliveryDate.Focus();
                    return;
                }
                string batchNo = txtBatchNo.Text.Trim();
                if (string.IsNullOrEmpty(batchNo))
                {
                    MessageBox.Show("批次不能为空！");
                    txtBatchNo.Focus();
                    txtBatchNo.SelectAll();
                    return;
                }

                if (lstOffShelves != null && lstOffShelves.Count != 0)
                {
                    if (MessageBox.Show("是否清空现有数据，重新获取", "提示消息", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    {
                        return;
                    }
                    else
                    {
                        lstOffShelves.Clear();
                    }
                }

                var result = Duty.OffShelvesOrderWCUIRule.NewInstance.GetOffShelvesListWC(batchNo, offDT, IsCellno);
                if (result != null && result.RESULT == "1")
                    lstOffShelves = result.DATA;
                if (lstOffShelves == null || lstOffShelves.Count==0)
                {
                    RefData();
                    MessageBox.Show("没有匹配条件的指令数据！");
                    return;
                }
                else if (lstOffShelves.Count > 0)
                {
                    MessageBox.Show(string.Format("指令数据{0}条，获取成功！", lstOffShelves.Count())); 
                    iSort = lstOffShelves.Count;
                }
                RefData();
            }
            catch (Exception ex)
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                txtGoodsCode.Focus();
                txtGoodsCode.SelectAll();
            }
        }

        private static int iSort = 0;
        //排序
        private void Sort(OffShelvesInfo offShelvesInfo)
        {
            offShelvesInfo.Sort = iSort;
            lstOffShelves.Sort((x, y) =>
            {
                return x.LOCATIONCODE.CompareTo(y.LOCATIONCODE);
            });
            this.dtGridOffShelves.Refresh();

            offShelvesInfo.Sort = iSort++;
        }
        //显亮当前行
        private void SelectionBright()
        {
            if (lstOffShelves == null )return;
            if (lstOffShelves.Count <= 0) return;
            //设置已扫描的为加亮
            if (string.IsNullOrEmpty(txtGoodsCode.Text)) return;
            string barCode = txtGoodsCode.Text.Trim();
            int curIndex = lstOffShelves.FindIndex(x => x.GOODSCODE == barCode);
            if (curIndex < 0) return;
            dtGridOffShelves.Select(curIndex);
            this.dtGridOffShelves.SelectionBackColor = Color.Green;
            
 
        }
        //刷新数据
        private void RefData()
        {
            this.bsOffShelvesSource.DataSource = null;
            this.bsOffShelvesSource.DataSource = lstOffShelves;
            this.dtGridOffShelves.DataSource = this.bsOffShelvesSource;
            this.dtGridOffShelves.Refresh();
            //设置已扫描的为加亮
            SelectionBright();
        }
  
        //回车批次号
        private void txtBatchNo_KeyDown(object sender, KeyEventArgs e)
        {
         
            if (e.KeyCode != Keys.Enter) return;

            if (string.IsNullOrEmpty(txtBatchNo.Text.Trim()))
            { 
                txtBatchNo.Focus();
            }
            txtGoodsCode.Focus();
            txtGoodsCode.SelectAll();
            
        } 
        //回车商品批次号
        private void txtGoodsBatchCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            if (string.IsNullOrEmpty(txtGoodsCode.Text.Trim())) return;
            string gdCode = txtGoodsCode.Text.Trim();

            if ((gdCode.Length != 9 && gdCode.Length != 12) || gdCode.Substring(0, 3) != "WOC")
            {
                MessageBox.Show("请扫描正确的WOC商品条码！");
                txtGoodsCode.SelectAll();
                return;
            } 
            try
            {
                
                int curIndex=-1;
                if (lstOffShelves != null)
                {
                    curIndex = lstOffShelves.FindIndex(x => x.GOODSCODE == gdCode);
                }
                else
                {
                    MessageBox.Show("请先获取下架指令！");
                    return;
                }
                if (curIndex >= 0)
                {
                    txtQty.Text = ((double)lstOffShelves[curIndex].QTY).ToString();
                    txtQty.Focus();
                    txtQty.SelectAll();
                    OffShelvesInfo curItem = lstOffShelves[curIndex];
                    lstOffShelves.Remove(curItem);
                    lstOffShelves.Insert(0, curItem);
                    RefData(); 
                    //lstOffShelves.Remove(curItem);
                    //lstOffShelves.Add(curItem);
                    //txtQty.Text = GetRestQty(gdCode).ToString();  
                    //Sort(lstOffShelves[curIndex]);
                }
                else if (curIndex < 0 )
                {
                    var result = Duty.OffShelvesOrderWCUIRule.NewInstance.CheckGoodsLocationInfo(gdCode).DATA;
                    if (result == null)
                    {
                        MessageBox.Show(string.Format("{0}无该商品数据！", gdCode));
                        return;
                    }
                    if (result.LOCATIONID == 0)
                    {
                        MessageBox.Show(string.Format("{0}无货位关联数据！", gdCode));
                        return;
                    }
                    else
                    {
                        MessageBox.Show(string.Format("{0}无匹配指令数据！", gdCode));
                        return;
                    }
                   

                } 


                RefData();
                txtQty.Focus();
                txtQty.SelectAll();
            }
            catch (Exception ex)
            {
                txtGoodsCode.Focus();
                txtGoodsCode.SelectAll();
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                //txtGoodsBatchCode.Focus();
                //txtGoodsBatchCode.SelectAll();
            }
            
        }
        //回车数量
        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            string gdCode = txtGoodsCode.Text.Trim();
            string textoffQty = txtQty.Text.Trim();
            decimal offQty = 0;
            if (string.IsNullOrEmpty(textoffQty))
            {
                MessageBox.Show("下架数量不能为空！");
                return; 
            } 
            if (string.IsNullOrEmpty(gdCode))
            {
                MessageBox.Show("扫描商品编码为空！");
                return;
            }
            try
            {
                try
                {
                    offQty = Convert.ToDecimal(textoffQty);
                }
                catch
                {
                    WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不正确!");
                    this.txtQty.Text = string.Empty;
                    this.txtQty.Focus();
                    return;
                }

                if (offQty <= 0)
                {
                    MessageBox.Show("下架数量不能小于等于0！");
                    return;
                }
                
                int curIndex = lstOffShelves.FindIndex(x => x.GOODSCODE == gdCode);
                if (curIndex >= 0)
                { 
                    decimal planQty = lstOffShelves[curIndex].QTY; 
                   
                    if (offQty > planQty)
                    {
                        if (MessageBoxEx.Question(string.Format("下架数量:{0},大于计划下架数量:{1},是否继续下架？", offQty, planQty)) == DialogResult.No)
                            return;
                    }
                    lstOffShelves[curIndex].QTYEXCE = offQty;
                    OffShelvesInfo lastItem = lstOffShelves[curIndex]; 
                    lstOffShelves.RemoveAt(curIndex);
                    lstOffShelves.Add(lastItem); 
                    //this.bsOffShelvesSource.DataSource = null;
                    //this.bsOffShelvesSource.DataSource = lstOffShelves;
                    //this.dtGridOffShelves.DataSource = this.bsOffShelvesSource;
                    this.dtGridOffShelves.Refresh(); 
 
                    txtQty.Text = string.Empty;
                    txtGoodsCode.Text = string.Empty; 
                    txtGoodsCode.Focus();
  
                }
                else
                {
                    txtGoodsCode.Focus();
                    txtGoodsCode.SelectAll();
                    WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("请重新扫描商品编码！"); 
                }
               
            }
            catch (Exception ex)
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
 
        } 
        //提交
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstOffShelves == null || lstOffShelves.Count == 0)
                {
                    MessageBox.Show("数据为空，无法提交！");
                    return;
                }
                
                Cursor.Current = Cursors.WaitCursor;
 
                List<OffShelvesInfo> lstOffQtys=lstOffShelves.FindAll(x => x.QTYEXCE > 0);
                if(lstOffQtys==null || lstOffQtys.Count==0)
                {
                    MessageBox.Show("下架数量都为0，\n请重新扫描下架数据！");
                    return;
                }
                 
                foreach (OffShelvesInfo oslItem in lstOffQtys)
                {
                    if (oslItem.QTY != oslItem.QTYEXCE)
                    {
                        if (MessageBox.Show("同一商品：" + oslItem.GOODSNAME + ",实下数[" + oslItem.QTYEXCE + "]与计划数[" + oslItem.QTY + "]不相等,是否继续提交？", "提示消息", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                        {
                            Sort(oslItem);
                            return;
                        }
                    }
                }
 
                if (lstOffQtys.Count() > 0)
                {
                    
                    ResultModel<bool> re = Duty.OffShelvesOrderWCUIRule.NewInstance.SetOffShelvesWC(LoginBean.Instance.USERCODE, lstOffQtys);
 
                    if (re.RESULT=="1")
                    {
                        //lstOffShelves.Clear();
                        lstOffShelves = lstOffShelves.FindAll(x => x.QTYEXCE == 0);
                        RefData();
                        //this.bsOffShelvesSource.DataSource = null;
                        //this.dtGridOffShelves.DataSource = this.bsOffShelvesSource;
                        //this.dtGridOffShelves.Refresh();

                        txtGoodsCode.Text = string.Empty; 
                        txtQty.Text = string.Empty;

                        dtDeliveryDate.Enabled = true;
                        txtBatchNo.ReadOnly = false;
                        txtBatchNo.Focus();
                        WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(string.Format("指令成功提交{0}条！\n剩余下架指令{1}条.", lstOffQtys.Count(), lstOffShelves.Count()));
                    }
                    else
                    {
                        MessageBox.Show("提交失败！\n" + re.MESSAGE);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        //关闭窗体事件
        private void FrmOffShelvesOrder_Closed(object sender, EventArgs e)
        {
            //System.Reflection.Assembly ass = System.Reflection.Assembly.Load("WoChu.RfClient.Login");
            //Type type = ass.GetType("WoChu.RfClient.Login.FrmMain");
            //Object o = Activator.CreateInstance(type);
            //System.Reflection.MethodInfo mi = type.GetMethod("Show");

            //mi.Invoke(o, null);
            //goodsBox = null;
            lstOffShelves = null;
            //lstOffCellNo = null;
            this.Close();
            this.Dispose();
        }
        //关闭窗体提示
        private void FrmOffShelvesOrder_Closing(object sender, CancelEventArgs e)
        {
            if (lstOffShelves != null)
            {
                if (lstOffShelves.Count > 0)
                {
                    if (MessageBox.Show("是否退出界面，将不保存界面数据？", "提示消息", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            }
            
        }
 
        //双击删除数据
        private void dtGridOffShelves_DoubleClick(object sender, EventArgs e)
        {
            int curIndex = dtGridOffShelves.CurrentRowIndex;
            if (curIndex < 0) return;
            try
            { 
                 string gdCode = dtGridOffShelves[curIndex, 1].ToString(); 
                OffShelvesInfo curItem = lstOffShelves.Find(x => x.GOODSCODE == gdCode); 
                string gbName = curItem.GOODSNAME;

                string Message = string.Format(" 商品编码:{0}, 名称:{1}  \n 是否删除该数据？", gdCode, gbName);
                if (MessageBoxEx.Question(Message) == DialogResult.Yes)
                {
                    lstOffShelves.Remove(curItem);
  
                    this.bsOffShelvesSource.DataSource = null;
                    this.bsOffShelvesSource.DataSource = lstOffShelves;
                    this.dtGridOffShelves.DataSource = this.bsOffShelvesSource;
                    this.dtGridOffShelves.Refresh();
                    if (lstOffShelves == null || lstOffShelves.Count == 0)
                    {
                        dtDeliveryDate.Enabled = true;
                        txtBatchNo.ReadOnly = false;
                    }
                    else
                    { 
                        dtDeliveryDate.Enabled = false;
                        txtBatchNo.ReadOnly = true;
                    }
                }
            }
            catch (Exception ex)
            {
                TraceEx.Write(ex.Message);
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("删除数据失败!");
            }
            finally
            {
                txtGoodsCode.Focus(); 
                txtGoodsCode.SelectAll();
            }
        }
        //单击选择数据
        private void dtGridOffShelves_Click(object sender, EventArgs e)
        {
            int curIndex = dtGridOffShelves.CurrentRowIndex;
            if (curIndex < 0) return;
            try
            {
                string gdCode = dtGridOffShelves[curIndex, 1].ToString();
                OffShelvesInfo curItem = lstOffShelves.Find(x => x.GOODSCODE == gdCode);
                dtGridOffShelves.Select(curIndex);
                this.dtGridOffShelves.SelectionBackColor = Color.Green; 
                txtGoodsCode.Text = curItem.GOODSCODE.ToString();
                txtQty.Text = curItem.QTYEXCE.ToString();
                txtQty.Focus();
                txtQty.SelectAll();
            }
            catch (Exception ex)
            {
                TraceEx.Write(ex.Message);
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("选择数据失败!");
            } 
        } 

        //配送日期验证
        private void dtDeliveryDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            string txtDeliDate = dtDeliveryDate.Value.ToShortDateString(); 
            if (string.IsNullOrEmpty(txtDeliDate))
            {
                MessageBox.Show("配送日期不能为空！");
                return;
            }
            txtBatchNo.Focus();
            txtBatchNo.SelectAll();
        }

       
    }
}